myApp.controller('ServerConfigController', function ($scope, $stateParams, $http, $timeout, $uibModal) {
    $timeout(function () {
        $('.center_div,.center_div button').css('font-family', '微软雅黑');
    }, 100);
    $scope.env = {};
    $scope.envNames = new Array();
    $scope.env.name = '';
    $scope.ws = null;
    $scope.projectNames = new Array();
    $scope.types = ['tomcat', 'php', 'ant_android', 'spring_boot_jar'];
    $scope.jumpServerList = [];
    $scope.toggle = function (panelId) {
        $('#' + panelId).collapse('toggle');
    };
    $scope.changeEnv = function () {
        $scope.switchEnv();
    };
    $scope.switchEnv = function () {
        $scope.loadEnv();
    };
    $scope.loadAreaStatus = function (areaName, async) {
        if (async != false) {
            async = true;
        }
        $.ajax({
            type: "post",
            url: java_url + "/beetle/deploy/loadAreaStatus",
            data: {evnName: $scope.env.name, areaName: areaName, tokenId: getTokenId()},
            dataType: "JSON",
            async: async,
            success: function (data) {
                if (!data.data) {
                    return;
                }
                data = data.data.areaStatus;
                var bindData = function bindData() {
                    var area = $scope.getAreaByName(areaName);
                    if (!area) {
                        return;
                    }
                    $scope.updateAreaStatus(area, data);
                }
                if (async) {
                    $scope.$apply(function () {
                        bindData();
                    });
                } else {
                    bindData();
                }

            },
            complete: function (xhr, status) {
            }
        });
    }
    $scope.updateAreaStatus = function (area, data) {
        if (!area || !data) {
            return;
        }
        if (data.status) {
            area.status = data.status;
        } else {
            area.status = 'ready';
        }
    }
    $scope.getAreaByName = function (areaName) {
        var targetArea;
        angular.forEach($scope.env.areas, function (area) {
            if (area.name == areaName) {
                targetArea = area;
                return;
            }
        });
        return targetArea;
    };
    $scope.initProjects = function () {
        $.ajax({
            type: "post",
            url: java_url + "/beetle/deploy/getAllTrunkProjects",
            data: {tokenId: getTokenId()},
            dataType: "JSON",
            success: function (data) {
                if (data.code != '0') {
                    alert('error code ' + data.code + ',desc=' + data.desc);
                    return;
                }
                $scope.$apply(function () {
                    angular.forEach(data.data.projects, function (pro) {
                        $scope.projectNames.push(pro.projectName);
                    });
                });
            }
        });
    };
    $scope.registerMessageQueue = function () {
        if ($scope.ws != null) {
            $scope.ws.close();
            $scope.ws = null;
        }
        ;
        $scope.ws = new WebSocket(getMQIP());
        $scope.ws.onopen = function () {
            angular.forEach($scope.env.areas, function (area) {
                $scope.ws.send("release-" + $scope.env.name + "-" + area.name + "-" + "status");
            });
        };
        $scope.ws.onmessage = function (event) {
            //log(event.data,'');
            var data = eval('(' + event.data + ')');
            $scope.$apply(function () {
                if (data.head.type == 'areaStatus') {
                    $scope.updateAreaStatus($scope.getAreaByName(data.head.areaName), data.body);
                }
            });
        }
    };
    $scope.loadEnvNames = function (async) {
        if (async != false) {
            async = true;
        }
        $.ajax({
            type: "post",
            url: java_url + "/beetle/deploy/loadEnvNames",
            data: {tokenId: getTokenId()},
            dataType: "JSON",
            async: async,
            success: function (data) {
                if (data.code != '0') {
                    alert('error code ' + data.code + ',desc=' + data.desc);
                    return;
                }
                data = data.data.envNames;
                var bindData = function bindData() {
                    if (data) {
                        $scope.envNames = data;
                        if (data.length > 0) {
                            $scope.env.name = $scope.envNames[0];
                        }
                    }
                }
                if (async) {
                    $scope.$apply(function () {
                        bindData();
                    });
                } else {
                    bindData();
                }

            },
            complete: function (xhr, status) {
            }
        });
    };
    $scope.loadEnv = function (async) {
        if (async != false) {
            async = true;
        }
        $.ajax({
            type: "post",
            url: java_url + "/beetle/deploy/loadEvn",
            data: {evnName: $scope.env.name, tokenId: getTokenId()},
            dataType: "JSON",
            async: async,
            success: function (data) {
                if (data.code != '0') {
                    alert('error code ' + data.code + ',desc=' + data.desc);
                    return;
                }
                data = data.data;
                var bindData = function bindData() {
                    if (data && data.list && data.list.length > 0) {
                        data = data.list[0];
                        $scope.env = data;
                        angular.forEach($scope.env.areas, function (area) {
                            $scope.loadAreaStatus(area.name, false);
                        });
                        $scope.registerMessageQueue();
                    }
                }
                if (async) {
                    $scope.$apply(function () {
                        bindData();
                    });
                } else {
                    bindData();
                }

            },
            complete: function (xhr, status) {
            }
        });
    };
    $scope.saveServerConfig = function (valid) {
        if (!valid) {
            return;
        }
        //生成id
        angular.forEach($scope.env.areas, function (area) {
            angular.forEach(area.tasks, function (task) {
                task.id = $scope.env.name + '-' + area.name + '-' + task.group + '-' + task.name + '-' + task.ip + '-' + task.httpPort;
            });
        });
        $.ajax({
            type: "POST",
            url: java_url + "/beetle/deploy/saveEnv?tokenId=" + getTokenId(),
            data: JSON.stringify($scope.env),
            contentType: "application/json; charset=utf-8",
            dataType: "JSON",
            beforeSend: function () {
                $('#btnSave').button("loading");
            },
            success: function (data) {
                if (data.code != '0') {
                    alert('error code:' + data.code + ',desc=' + data.desc);
                    return;
                } else {
                    alert('result code:' + data.code + ',desc=' + data.desc);
                    $scope.switchEnv();
                }
            },
            complete: function (xhr, status) {
                $('#btnSave').button("reset");
            }
        });
    }
    $scope.saveServerAreaConfig = function (valid) {
        if (!valid) {
            return;
        }
        var area = this.area;
        var btnId = 'btnSave' + this.$index;
        //生成id
        angular.forEach(area.tasks, function (task) {
            task.id = $scope.env.name + '-' + area.name + '-' + task.group + '-' + task.name + '-' + task.ip + '-' + task.httpPort;
        });
        $.ajax({
            type: "POST",
            url: java_url + "/beetle/deploy/saveArea/" + $scope.env.name + "?tokenId=" + getTokenId(),
            data: JSON.stringify(area),
            contentType: "application/json; charset=utf-8",
            dataType: "JSON",
            beforeSend: function () {
                $('#' + btnId).button("loading");
            },
            success: function (data) {
                if (data.code != '0') {
                    alert('error code:' + data.code + ',desc=' + data.desc);
                    return;
                } else {
                    alert('result code:' + data.code + ',desc=' + data.desc);
                    $scope.switchEnv();
                }
            },
            complete: function (xhr, status) {
                $('#' + btnId).button("reset");
            }
        });
    }
    $scope.isRunning = function () {
        var isRunning = false;
        angular.forEach($scope.env.areas, function (area, index) {
            if (area.status == 'running') {
                isRunning = true;
                return;
            }
        });
        return isRunning;
    }
    $scope.minusArea = function () {
        if (!window.confirm('确定要删除区域[' + this.area.alias + ']?')) {
            return;
        }
        var area = this.area;
        $.ajax({
            type: "POST",
            url: java_url + "/beetle/deploy/removeArea",
            data: {
                envName: $scope.env.name,
                areaName: area.name,
                tokenId: getTokenId()
            },
            success: function (data) {
                if (data.code != '0') {
                    alert('error code:' + data.code + ',desc=' + data.desc);
                    return;
                }
                $scope.switchEnv();
            }
        });
        /*$scope.env.areas.splice(this.$index,1);
         $('#myTab li.active').removeClass('active');
         $('#myTabContent .tab-pane').removeClass('active in');
         $timeout(function(){
         $('#myTab li:eq(0)').addClass('active');
         $('#myTabContent .tab-pane:eq(0)').addClass('active in');
         },200);*/
    }
    $scope.checkPort = function () {
        var exist = false;
        var curTask = this.task;
        angular.forEach(this.$parent.area.tasks, function (task) {
            if (curTask != task && curTask.ip == task.ip && curTask.port == task.port) {
                exist = true;
                return;
            }
        });
        return !exist;
    };
    $scope.checkHttpPort = function () {
        var exist = false;
        var curTask = this.task;
        if(curTask.httpPort == 0 || curTask.httpPort == '' || curTask.httpPort == null){
            return !exist;
        }
        angular.forEach(this.$parent.area.tasks, function (task) {
            if (curTask != task && curTask.ip == task.ip && curTask.httpPort == task.httpPort) {
                exist = true;
                return;
            }
        });
        return !exist;
    };
    $scope.checkJmxPort = function () {
        var exist = false;
        var curTask = this.task;
        if(curTask.jmx_port == 0 || curTask.jmx_port == '' || curTask.jmx_port == null){
            return !exist;
        }
        angular.forEach(this.$parent.area.tasks, function (task) {
            if (curTask != task && curTask.ip == task.ip && curTask.jmx_port == task.jmx_port) {
                exist = true;
                return;
            }
        });
        return !exist;
    };
    $scope.checkAgentPort = function () {
        return true;
        // var exist = false;
        // var curTask = this.task;
        // if(curTask.agent_port == 0 || curTask.agent_port == '' || curTask.agent_port == null){
        //     return !exist;
        // }
        // angular.forEach(this.$parent.area.tasks, function (task) {
        //     if (curTask != task && curTask.ip == task.ip && curTask.agent_port == task.agent_port) {
        //         exist = true;
        //         return;
        //     }
        // });
        // return !exist;
    };
    $scope.checkDubboPort = function () {
        var exist = false;
        var curDubbo = this.dubbo;
        angular.forEach(this.$parent.area.dubboList, function (dubbo) {
            if (curDubbo != dubbo && curDubbo.dubboIp == dubbo.dubboIp && curDubbo.dubboPort == dubbo.dubboPort) {
                exist = true;
                return;
            }
        });
        return !exist;
    }
    $scope.checkPorts = function () {
        var exist = false;
        //angular.forEach($scope.env.areas,function(area){
        var area = this.area;
        if (exist)return false;
        //检查应用端口重复
        angular.forEach(area.tasks, function (curTask) {
            if (exist)return;
            if(curTask.type != 'tomcat'&& curTask.type != 'php'){
                return;
            }
            angular.forEach(area.tasks, function (task) {
                if (exist)return;
                //if(curTask!=task&&curTask.ip==task.ip&&(curTask.port==task.port||curTask.httpPort==task.httpPort)){
                if (curTask != task && curTask.ip == task.ip && curTask.httpPort == task.httpPort) {
                    exist = true;
                    return;
                }
            });
        });
        if (exist)return false;
        //检查dubbo端口重复
        angular.forEach(area.dubboList, function (curDubbo) {
            if (exist)return;
            angular.forEach(area.dubboList, function (dubbo) {
                if (exist)return;
                if (curDubbo != dubbo && curDubbo.dubboIp == dubbo.dubboIp && curDubbo.dubboPort == dubbo.dubboPort) {
                    exist = true;
                    return;
                }
            });
        });
        //});
        return !exist;
    }
    $scope.openAddEnvAreaModal = function (size) {
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'AddEnvAreaModal.html',
            controller: 'AddEnvAreaModalCtrl',
            size: size,
            resolve: {
                areas: function () {
                    return $scope.env.areas;
                }
            }
        });
        modalInstance.result.then(function (result) {
            $scope.addArea(result.areaName, result.areaAlias,result.zoneCode);
        }, function () {
            //dismiss
        });
    }
    $scope.addArea = function (areaName, areaAlias,zoneCode) {
        var area = {
            "name": areaName,
            "alias": areaAlias,
            "zone_code": zoneCode,
            "description": "",
            "status": "ready",
            "groups": ["A", "B"],
            "jumpServerIp": "",
            "useJumpServer": false,
            tasks: []
        };
        $scope.env.areas.push(area);
    }
    $scope.addTask = function () {
        var newTask = {
            "id": "",
            "group": "A",
            "name": "",
            "ip": "",
            "type": "",
            "dstUser": "beetle",
            "port": 0,
            "configPath": "",
            "status": [],
            "statusMsg": "",
            "serverPath": "",
            "javaHome": "",
            "httpPort": 0,
            "jmx_port": 0,
            "agent_port": 0,
            "is_resource": "0",
            "editable": true
        };
        if (!this.area.tasks) {
            this.area.tasks = new Array();
        }
        this.area.tasks.push(newTask);
    }
    $scope.addDubbo = function () {
        var newDubbo = {
            "dubboIp": "",
            "dubboPort": 0,
            "userName": "",
            "userPass": "",
            "editable": true
        };
        if (!this.area.dubboList) {
            this.area.dubboList = new Array();
        }
        this.area.dubboList.push(newDubbo);
    }
    $scope.removeTask = function () {
        this.$parent.area.tasks.splice(this.$index, 1);
    }
    $scope.removeDubbo = function () {
        this.$parent.area.dubboList.splice(this.$index, 1);
    };
    $scope.loadJumpServerList = function () {
        $http.post(java_url + '/beetle/jumpServer/getJumpServerList', {
            tokenId: getTokenId()
        }).success(function (data) {
            $scope.jumpServerList = [];
            if (data.code == '0') {
                if (data.data.count == 0) {
                    return;
                } else {
                    $scope.jumpServerList = data.data.list;
                    return;
                }
                ;
            } else if (data.code == '2') {
                window.location.href = "/beetle/App/module/login/tpl/login.html";
                return;
            } else {
                alert(data.desc);
                return;
            }
            ;
        });
    }
    $scope.setModifiable = function (objName) {
        this[objName].modifiable = !this[objName].modifiable;
    }
    $scope.loadJumpServerList();
    $scope.loadEnvNames(false);
    $scope.switchEnv();
    $scope.initProjects();
});

myApp.controller('AddEnvAreaModalCtrl', function ($scope, $uibModalInstance, areas) {
    $scope.areaName = '';
    $scope.areaAlias = '';
    $scope.zoneCode = '';
    $scope.ok = function (valid) {
        if (!valid) {
            return;
        }
        $scope.areaName = $.trim($scope.areaName);
        $scope.areaAlias = $.trim($scope.areaAlias);
        $scope.zoneCode = $.trim($scope.zoneCode);
        $uibModalInstance.close({areaName: $scope.areaName, areaAlias: $scope.areaAlias,zoneCode:$scope.zoneCode});
    };
    $scope.checkAlias = function () {
        var exist = false;
        angular.forEach(areas, function (area) {
            if ($scope.areaAlias == area.alias) {
                exist = true;
                return;
            }
        });
        return !exist;
    };
    $scope.checkCode = function () {
        var exist = false;
        angular.forEach(areas, function (area) {
            if ($scope.zoneCode == area.zone_code) {
                exist = true;
                return;
            }
        });
        return !exist;
    };
    $scope.checkAreaName = function () {
        var exist = false;
        angular.forEach(areas, function (area) {
            if ($scope.areaName == area.name) {
                exist = true;
                return;
            }
        });
        return !exist;
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});